import { message } from 'antd'
import { cloneDeep, merge} from 'lodash'
import { hashHistory } from 'dva/router'
import {queryAllAddress,getDetail,AllEstateList,allActivityList,submit,getArea,getType,getKeys} from './codeChannelEditServ.js'
import { makeAddress,download } from "utils/util"

// const delay = (ms) => new Promise((resolve) => {

//   setTimeout(resolve, ms);

// });
const defultState = {
      //推荐楼盘
      query2:{
        regionId:'',//区域id
        productId:'',//项目id
        channelType:'',//传播渠道类别
        channelName:'',//传播渠道名称
        remark:'',
        regionName:'',
        imgUrl:''
      },
      location:'',
      showUl:false,
      scan:false,
      clique:'',
      city:[],
      actionType:'',
      areaList1:[],
      projectList:[],
      visible:false,
      value:1,
      productName:'',
      codeId:'',
      list:[],
      biz:{
        1: {
          queryForm: {},
          rowSelection_type:'radio',
          selectedRowKeys:[]
        },
        2: {
          queryForm: {}  ,
          rowSelection_type:'radio',
          selectedRowKeys:[]
        },
      },
      biz2:{
        queryForm: {},
        rowSelection_type:'radio',
      },
      hrefModalObj:{
        visible:false,
        jumpLocation:'',
      },
      currentItem:[],
      btnLoading:false,
      regions:[],
      products:[],
      types:[],
      query1:{},
      roleType:'',
      show:true,
      showAll:false,
  }
  
  const tmpModule = {
    state: cloneDeep(defultState),
    subscriptions: {
      setup ({dispatch, history}) {
        let clique=localStorage.getItem('clique')
        history.listen(({ pathname, query }) => {
          let query1 = query
          if('' + tmpModule.pathname === '' + pathname){
            
            dispatch({ type: 'updateStore', payload:{...cloneDeep(defultState),roleType:localStorage.getItem('roleType')} });
            dispatch({ type: 'updateStore', payload:{query1} });
            dispatch({type: 'getAreaList', payload: {}})
            dispatch({type: 'getArea', payload: {}})
            dispatch({type: 'getType', payload: {}})
            if(query1.actionType=='detail'){
              dispatch({type: 'getDetail', payload: {id:query1.id}})
            }
          }
        })
      }
    },
    effects: {
        //获取省市
      *getAreaList({ payload }, { put, call, select }){
        let {actionType}=yield select((state)=>state[tmpModule.namespace])
          const { data, success } = yield call(queryAllAddress);
          if(success) {
            let areaList1 = []
            let arr = [data[0]]
            let attr = [data[data.length-1]]
            data[0] = {
              label:"北京",
              value:"110100",
              children:arr
            }
            data[data.length-1]={
              label:"澳门",
              value:"820000",
              children:attr
            }
            //去掉第三级，
            areaList1 = makeAddress(data,2)
           yield put({ type: 'updateStore',payload:{areaList1}})
      }
    },
        //获取区域
        *getArea({payload},{put,call,select}){
          const {data,success}=yield call(getArea,payload)
          if(success){
            let {query1}=yield select((state)=>state[tmpModule.namespace])
            yield put({type:'updateStore',payload:{regions:data}})
           
          }
        },
        //获取二维码类别
        *getType({payload},{put,call,select}){
          
          const {data,success}=yield call(getType,payload)
          if(success){
            yield put({type:'updateStore',payload:{types:data}})
          }
        },
        //获取活动详细信息
        *getDetail({ payload }, { put, call, select }){
          
          let { data, success } = yield call(getDetail,payload);
          if(success) {
          //回来的数据回显
          // debugger
          let {city,areaList1,currentItem,regions,location}=yield select((state)=>state[tmpModule.namespace])
          let products=[]
          regions.map((item)=>{
            if(item.value==data.data.regionId){
              products=item.products
            }
          })
          let hrefModalObj = {}
          hrefModalObj.jumpUrl = data.data.jumpUrl
          hrefModalObj.jumpLocation = data.data.jumpLocation
          hrefModalObj.productName = data.data.productName
          hrefModalObj.channelTypeName = data.data.channelTypeName
          hrefModalObj.busiName = data.data.busiName
          location=data.data.jumpLocation
         
          //(1:推介 2：内部链接 3：资讯 4:外部链接 5：活动，6：预约看房，7：美房详情)
          if(['1'].indexOf(data.data.jumpLocation+"")>-1){
            currentItem=[data.data.productId]
          }else if(['2'].indexOf(data.jumpLocation+"")>-1){
            currentItem=[data.data.contentId]
          }
          hrefModalObj.params = {contentId:data.data.contentId,productId:data.data.productId,btnName:data.data.btnName}
          let query2=data.data
          // query2.productId=data.data.productName
          console.log()
          if(!query2.productId){
            query2.productName='全部'
          }
          if(!query2.regionId){
            query2.regionId='全部'
          }
          yield put({ type: 'getActivityList',payload:{businessId:data.data.productId}})
          yield put({ type: 'updateStore',payload:{city,query2,hrefModalObj,currentItem,products,location,scan:true}})

          }
         
        },
        
          //提交表单
          *submit({payload},{put,call,select}){
            try{
              yield put({ type: 'updateStore',payload:{btnLoading:true}})
              let {query2,hrefModalObj,actionType,codeId,scan,currentItem}=yield select((state)=>state[tmpModule.namespace])
              let objParmas = {}
                let params = hrefModalObj.params
                // query2.linkType = hrefModalObj.jumpLocation
                if(hrefModalObj.jumpLocation=='1'){
                  hrefModalObj.jumpUrl='pages/biz/buildingDetail/buildingDetail'
                  console.log(!hrefModalObj.busiId)
                  if(!hrefModalObj.busiId){
                    params={
                      ...params,
                      busiId:query2.productId
                    }
                    console.log(params.busiId)
                  }
                }
                
                objParmas = {
                  ...cloneDeep(query2),
                  ...cloneDeep(hrefModalObj),
                  ...params
                }
                if(payload.opsType==='2'){
                  codeId=''
                  scan=true
                }
                if(hrefModalObj.jumpLocation=='1'&& hrefModalObj.params &&query2.productId!=hrefModalObj.params.busiId&&query2.productId!=0){
                  message.error('所属项目与楼盘跳转项目必须一致')
                }else{
                  if(hrefModalObj.jumpUrl==''){
                    message.error('请输入选择跳转路径')
                  }else if(hrefModalObj.jumpLocation==''){
                    message.error('请输入选择跳转位置')
                  }else{
                    let params={...objParmas,type:1,...payload,id:codeId}
                    if(params.productId==0){
                      params.busiId=currentItem[0]
                      delete params.productId
                    }
                    if(params.regionId==0){
                      delete params.regionId
                    }
                    console.log(params)
                    const {  success,data } = yield call(submit,params);
                    if(success){
                      if(payload.opsType==='1'){
                        hashHistory.push('/home/codeChannelAdmin/codeChannelList')
                        message.success('新增成功')
                      }
                      query2.imgUrl=data.imgUrl
                      codeId=data.id
                    }
                  }
                }
                // yield call(delay, 2000);
                yield put({ type: 'updateStore',payload:{btnLoading:false,codeId,query2,scan}})
              
            }catch(e){
              console.log(e)
            }
           
            
            
          },
          //获取所有上架楼盘列表
          *getAllEstateList({payload},{put,call,select}){
            let {projectList}=yield select((state)=>state[tmpModule.namespace])
            const { rows, success,total,pageNo } = yield call(AllEstateList,{shelfStatus: "1",pageSize:100000});
            if(success) {
              yield put({ type: 'updateStore',payload:{projectList:rows,projectListTotal:total,projectListPageNo:pageNo}})
            }
          },
          *getKeys({payload},{put,call,select}){
            let {projectList,list}=yield select((state)=>state[tmpModule.namespace])
            const { rows, success,total,pageNo } = yield call(getKeys,{...payload,pageSize:100000});
            if(success) {
              list=[]
              rows.map((item)=>{
                list.push(item.channelName)
              })
              yield put({ type: 'updateStore',payload:{list}})
            }
          },
          * dealEditor({ payload }, { put, select }) {
            let { query2 } = yield select(state => state[tmpModule.namespace])
            let newDetail=Object.assign({}, query2)
            newDetail.content=payload.detail
            yield put({ type: 'updateStore', payload: { query2: newDetail } });
          },
       
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        console.log(preState)
        return Object.assign({}, preState, action.payload)
      },
    }
  }  
  export default tmpModule
  
